//
// Created by 崔世强 on 2018/6/7.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import WCDBSwift
import SwiftyJSON

class MessageService {
    var db: Database
    
    init() {
        db = SQLiteHelper.getDb()
    }
    
    func getMessages(sessionServerId:Int,chatType:ChatType,date:Date = Date(),pageSize:Int) -> [ChatMessage]{
        var chatMsgs = [ChatMessage]()
        do {
            let msgs:[Message] = try db.getObjects(on: Message.CodingKeys.all, fromTable: Message.table,
                                                   where: Message.CodingKeys.deleted == false && Message.CodingKeys.sessionServerId == sessionServerId && Message.CodingKeys.chatType == chatType.rawValue && Message.CodingKeys.createTime < date,
                                                   orderBy: [Message.CodingKeys.createTime.order(.descending)],
                                                   limit: pageSize)
            //升序排序
            let sortedMsgs = msgs.sorted {$0.createTime.timeIntervalSince1970 < $1.createTime.timeIntervalSince1970}
            for row in sortedMsgs {
                let friend:Contact? = try db.getObject(on: Contact.CodingKeys.all, fromTable: Contact.table, where: Contact.CodingKeys.userId == row.userId)
                let userName = friend?.remarkName ?? friend?.name ?? "\(row.userId)"
                let dateTime = row.createTime.timeIntervalSince1970
                
                let chatMsg = ChatMessage(sessionId: row.sessionServerId, from: row.userId, fromName: userName, me: row.me ? 1: 0,messageType: row.messageType)
                chatMsg.localId = row.id
                chatMsg.avatar = friend?.avatar
                chatMsg.ts = dateTime
                chatMsg.text = row.content ?? ""
                chatMsg.status = row.status
                chatMsg.read = row.audioRead
                chatMsg.chatType = chatType
                if row.me {
                    chatMsg.avatar = AppStatusManager.instance.avatar
                    chatMsg.fromName = AppStatusManager.instance.userLoginStatus.2 ?? "\(chatMsg.from)"
                }
                switch chatMsg.messageType {
                case .audio:
                    let ss = chatMsg.text!.split(separator: "|")
                    chatMsg.audioPath = String(ss[0])
                    chatMsg.audioDuration = Double(String(ss[1]))
                    break
                case .img:
                    let json = JSON.init(parseJSON: chatMsg.text ?? "")
                    chatMsg.imgFileName = json["fileName"].stringValue
                    let dataStr = json["data"].stringValue
                    chatMsg.imgData = Data(base64Encoded: dataStr)
                    chatMsg.memSize = json["size"].intValue
                    let width = json["width"].doubleValue
                    let height = json["height"].doubleValue
                    chatMsg.imgSize = CGSize(width: width, height: height)
                    break
                case .sticker:
                    let json = JSON.init(parseJSON: chatMsg.text ?? "")
                    chatMsg.stickerPath = json["sticker"].stringValue
                    chatMsg.category = json["category"].stringValue
                    chatMsg.stickerName = json["name"].stringValue
                case .notice:
                    let text = NoticeHandlerFactory.instance.getHandler(chatMsg).show(chatMsg)
                    chatMsg.text = text
                    chatMsg.messageType = .notice
                case .file:
                    let json = JSON.init(parseJSON: chatMsg.text ?? "")
                    chatMsg.fileName = json["name"].stringValue
                    chatMsg.ext = json["ext"].stringValue
                    chatMsg.fileSize = json["size"].intValue
                    chatMsg.storeFile = json["remote"].stringValue
                    break
                case .video:
                    let json = JSON(parseJSON:chatMsg.text ?? "")
                    print(" == \(json["fileName"].stringValue)")
                    let videoFileName = json["fileName"].stringValue
                    let url = Common.getLocalUrl(videoFileName, file: "videoUrl")
                    
                    if  !FileManager.default.fileExists(atPath: url.path) {//如果本地没有视频
                        
                    }else {
                        //如果本地有视频
                        //存储视频第一帧图片, 以及宽高
                        if let img = VideoUtil.instance.getThumbnailImg(url: url) {
                            chatMsg.videoThumbnail = img
                            print("img.size == \(img.size)")
                            let size = Common.getImgSize(img.size)
                            chatMsg.videoWidth = size.width
                            chatMsg.videoHeight = size.height
                        }
                    }
                case .unknown:
                    chatMsg.text = "[未知消息类型，请升级app]"
                    chatMsg.messageType = .text
                    break
                default:
                    break
                }
                chatMsgs.append(chatMsg)
            }
        } catch {
            print(error)
        }
        return chatMsgs
    }
    
    func updateMsgReadState(msg:ChatMessage) {
        do {
            if let message = try  MessageDao.getMsg(id: msg.localId ?? 0) {
                message.audioRead = msg.read
                try MessageDao.updateMsgReadState(msg: message)
            }
        }catch {
            
        }
    }
    
    func deleteMsg(msg:ChatMessage) {
        do {
            if let message = try MessageDao.getMsg(id: msg.localId ?? 0 ) {
                try MessageDao.deleteMsg(msgId: msg.localId!, chatType: msg.chatType)
            }
        }catch {
            
        }
    }
    
    func readMsgs(sessionServerId:Int) {
        do {
            try db.run(transaction: { [unowned self]_ in
                let msgUpd = Message()
                msgUpd.unread = false
                try db.update(table: Message.table, on: Message.CodingKeys.unread, with: msgUpd,where: Message.CodingKeys.sessionServerId == sessionServerId && Message.CodingKeys.unread == 1)
            })
        }catch {
            
        }
    }
}
